/*
 * Copyright 2011-2025 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0.
 * See `LICENSE` in the project root for license information.
 */

package me.ijleex.platform.framework.util;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 日期/时间处理工具类.
 *
 * @author liym
 * @since 2025-03-06 20:33 新建
 */
public final class DateTimeUtils {

    private DateTimeUtils() {
        throw new IllegalAccessError("Utility class");
    }

    /**
     * 按小时分割时间段
     *
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @param interval 分隔小时
     * @return 分隔的时间范围
     * @since 2025-03-06 20:41
     */
    public static List<Map.Entry<LocalDateTime, LocalDateTime>> getPeriodsByHour(
            LocalDateTime startTime, LocalDateTime endTime, int interval) {
        if (startTime.isAfter(endTime)) {
            throw new IllegalArgumentException("startTime must be before endTime");
        }
        if (interval <= 0) {
            throw new IllegalArgumentException("interval must be > 0");
        }

        List<Map.Entry<LocalDateTime, LocalDateTime>> result = new ArrayList<>();
        LocalDateTime start = startTime;
        do {
            // 计算当前小时的结束时间（下一个整点）
            LocalDateTime truncated = start.truncatedTo(ChronoUnit.HOURS);
            LocalDateTime nextEnd = truncated.plusHours(interval);

            // 确定实际结束时间（取整点时间和最终结束时间的较小值）
            LocalDateTime end = nextEnd.isBefore(endTime) ? nextEnd : endTime;

            result.add(new AbstractMap.SimpleEntry<>(start, end));

            // 移动到下一个时间段
            start = end;
        } while (start.isBefore(endTime));
        return result;
    }

}
